package master;


import java.nio.channels.SeekableByteChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 * 字符串相乘
 *
 * @author chenyw
 * @date 2022/7/25 10:58
 */
public class M43multiply {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        String ans = "0";
        int m = num1.length(), n = num2.length();

        for (int i = n - 1; i >=0; i--) {
            StringBuffer curr = new StringBuffer();
            int add = 0;
            //先补零
            for (int j = n - 1; j > i; j--) {
                curr.append(0);
            }
            for (int j = m - 1; j >= 0; j--) {
                int product = (num1.charAt(j)- '0') * (num2.charAt(i) - '0') + add;
                curr.append(product % 10);
                add = product / 10;
            }
            if (add != 0) {
                curr.append(add);
            }
            //相加
            ans = addString(ans, curr.reverse().toString());
        }
        return ans;
    }

    private String addString(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        StringBuffer ans = new StringBuffer();
        while (i >= 0 || j >= 0 || add != 0) {
            int x = i >= 0 ? num1.charAt(i) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;
            ans.append((x + y + add) % 10);
            add = (x + y + add) / 10;
            i--;
            j--;
        }
        ans.reverse();
        return ans.toString();
    }
}
